package com.xcity.game.activity.limitbuy;

import java.util.ArrayList;
import java.util.List;

import com.xcity.db.entity.Player;
import com.xcity.game.activity.ActivityService;
import com.xcity.game.common.Cause;
import com.xcity.game.common.ItemResponse;
import com.xcity.game.common.MessageConst;
import com.xcity.game.common.PlayerPool;
import com.xcity.game.event.GameEvents;
import com.xcity.game.player.PlayerService;
import com.xcity.game.recharge.RechargeTemplate;
import com.xcity.pomelo.PomeloRoute;
import com.xcity.pomelo.request.DailyLimitBuyGetRewardRequest;
import com.xcity.pomelo.request.DailyLimitBuyInfoRequest;
import com.xcity.pomelo.response.DailyLimitBuyInfoResponse;
import com.xcity.pomelo.response.DailyLimitBuyRewardResponse;
import com.xcity.pomelo.response.HintResponse;

import naga.x.App;
import naga.x.event.Event;
import naga.x.event.EventListener;
import naga.x.game.template.TemplateService;
import naga.x.game.time.TimeUpdater;
import naga.x.net.Session;
import naga.x.net.annotation.OPHandler;
import naga.x.net.impl.pomelo.annotation.PomeloOP;
import naga.x.service.ServiceException;

/**
 * 每日限购(2元)
 * @author yang.li
 *
 */
@OPHandler
public class DailyLimitBuyActivityService extends ActivityService implements EventListener {

	protected static final int RECHARGE_ID = 10000;
	protected static final int NEED_RECHARGE_MONEY = 2; // 需充值金额
	
	public static final byte STATE_NO_BUY = 0; // 未购买
	public static final byte STATE_BOUGHT = 1; // 已购买但未领奖
	public static final byte STATE_RECEIVED = 2; // 已领奖
	
	protected RechargeTemplate template;
	protected List<ItemResponse> items; // 礼包
	protected int itemsNeedBagGridSize;
	
	@Override
	public void startup() throws ServiceException {
//		template = new RechargeTemplate();
//		template.setId(RECHARGE_ID);
//		template.setType((byte) -1);
//		template.setName("超值大礼包");
//		template.setCurrency("CNY");
//		template.setPrice(NEED_RECHARGE_MONEY);
//		template.setVisible(false); // 充值列表中对客户端不可见
//		App.getApp().getServiceManager().get(TemplateService.class).add(template);
		template = App.getApp().getServiceManager().get(TemplateService.class).get(RechargeTemplate.class, RECHARGE_ID);
		// TODO 礼包暂时写死
//		StringBuilder desc = new StringBuilder();
		items = new ArrayList<ItemResponse>(3);
		ItemResponse item = new ItemResponse(20017, 30); // 钻石
		items.add(item);
//		desc.append(item.getName()).append('x').append(item.getCount());
		item = new ItemResponse(20023, 100000); // 现金
		items.add(item);
//		desc.append(' ').append(item.getName()).append('x').append(item.getCount());
		item = new ItemResponse(10013, 4); // 玫瑰
		items.add(item);
//		desc.append(' ').append(item.getName()).append('x').append(item.getCount());
//		template.setDesc(desc.toString());
		itemsNeedBagGridSize = getItemsNeedBagGridSize();
		
		App.getApp().getEventManager().register(this);
	}

	@Override
	public void shutdown() throws ServiceException {
	}
	
	@PomeloOP(PomeloRoute.DAILY_LIMIT_BUY_INFO)
	protected void requestInfo(Session session, DailyLimitBuyInfoRequest req) {
		Player player = session.getClient();
		session.send(new DailyLimitBuyInfoResponse(req.getSerial(), getState(player), RECHARGE_ID, NEED_RECHARGE_MONEY, items));
	}
	
	@PomeloOP(PomeloRoute.DAYLY_LIMIT_BUY_GET_REWARD)
	protected void requestGetReward(Session session, DailyLimitBuyGetRewardRequest req) {
		Player player = session.getClient();
		byte state = getState(player);
		switch (state) {
			case STATE_NO_BUY:
				session.send(new HintResponse(req.getSerial(), MessageConst.GET_REWARD_WHEN_NO_BUY));
				break;
			case STATE_RECEIVED:
				session.send(new HintResponse(req.getSerial(), MessageConst.REWARD_ALREADY_RECEIVED));
				break;
			case STATE_BOUGHT:
				if (player.getBag().getFreeSize() < itemsNeedBagGridSize) {
					session.send(new HintResponse(req.getSerial(), MessageConst.BAG_FULL));
					return;
				}
				state = reward(player);
				session.send(new DailyLimitBuyRewardResponse(req.getSerial(), state));
				LOG.info("[DAILYLIMITBUY GOT]ID[{}]", player.getId());
				break;
		}
	}

	@Override
	public int[] getEventTypes() {
		return new int[] { GameEvents.EVENT_RECHARGE, GameEvents.EVENT_RECHARGE_OFFLINE };
	}

	@Override
	public void handleEvent(Event event) {
		switch (event.getType()) {
			case GameEvents.EVENT_RECHARGE:
			case GameEvents.EVENT_RECHARGE_OFFLINE:
				playerRecharge(event.getParameter(0), event.getParameter(1), event.getParameter(2));
				break;
		}
	}
	
	private void playerRecharge(Player player, int money, RechargeTemplate template) {
		if (template.getId() == RECHARGE_ID) {
			if (money >= NEED_RECHARGE_MONEY) {
				int lastDay = player.getPool().getIntValue(PlayerPool.PROPERTY_DAILY_LIMIT_BUY_LAST_DAY);
				if (lastDay != TimeUpdater.getInstance().today()) {
					if (!(player instanceof Player)) {
						// 尝试取在线玩家
						Player p = App.getApp().getServiceManager().get(PlayerService.class).getOnlinePlayer(player.getId());
						if (p != null) {
							player = p;
						}
					}
					player.poolSet(PlayerPool.PROPERTY_DAILY_LIMIT_BUY_LAST_DAY, TimeUpdater.getInstance().today());
					player.poolSet(PlayerPool.PROPERTY_DAILY_LIMIT_BUY_STATE, STATE_BOUGHT);
					LOG.info("[DAILYLIMITBUY RECHARGED]ID[{}]MONEY[{}]", player.getId(), money);
				} else {
					LOG.info("[DAILYLIMITBUY FAILED]ID[{}]MONEY[{}]CAUSE[DUPLICATE]", player.getId(), money);
				}
			} else {
				LOG.info("[DAILYLIMITBUY FAILED]ID[{}]MONEY[{}]CAUSE[RECHARGE NOT ENOUGH]", player.getId(), money);
			}
		}
	}
	
	private static byte getState(Player player) {
		int lastDay = player.getPool().getIntValue(PlayerPool.PROPERTY_DAILY_LIMIT_BUY_LAST_DAY);
		byte state = player.getPool().getByteValue(PlayerPool.PROPERTY_DAILY_LIMIT_BUY_STATE);
		if (lastDay != TimeUpdater.getInstance().today() && state == STATE_RECEIVED) {
			return STATE_NO_BUY;
		}
		return state;
	}
	
	private byte reward(Player player) {
		player.poolSet(PlayerPool.PROPERTY_DAILY_LIMIT_BUY_STATE, STATE_RECEIVED);
		for (ItemResponse item : items) {
			player.getBag().addItemWithoutException(item.getId(), item.getCount(), Cause.DAILY_LIMIT_BUY);
		}
		return STATE_RECEIVED;
	}
	
	private int getItemsNeedBagGridSize() {
		int size = 0;
		for (ItemResponse item : items) {
			if (!item.getTemplate().isAutoUse()) {
				int _size = (item.getCount() + item.getTemplate().getStack() - 1) / item.getTemplate().getStack();
				size += _size;
			}
		}
		return size;
	}
	

}
